/* eslint-disable no-restricted-syntax */
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  Table,
  Tabs,
  Card,
  Modal,
  AutoComplete,
  Form,
  Select,
  Menu,
  Row,
  Col,
  Radio,
  Tag,
  Pagination,
  DatePicker,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
// const { RangePicker } = DatePicker;
import { AppstoreOutlined, MailOutlined, SettingOutlined } from '@ant-design/icons';
import { EditOutlined, EllipsisOutlined } from '@ant-design/icons';
import './index.less';
import { FormattedMessage, history, Link } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { studioGetTypes, getModels, studioGetRelatedTypes } from './service';

//模型logo默认图片
import cvLogo from '@/assets/cv.png';
import nlpLogo from '@/assets/nlp.png';
import recommendLogo from '@/assets/recommend.png';
import speechLogo from '@/assets/speech.png';

import format from '@/utils/format';
import arouter from '@/utils/apulis-router';

//权限组件
import { AuthzHOC, AuthzProvider, useCheckAuth, checkAuth } from '@apulis/authz';
import style from './index.less';


const { SubMenu } = Menu;
const { Meta } = Card;
const ModelPage = (props) => {
  const abilityMap = {
    'train': '训练',
    'centerInfer': '中心推理',
    'edgeInfer': '边缘推理'
  };
  const sourceMap = {
    'publish': '用户发布',
    'preset': '预置'
  };
  const [totalMenuInfo, setTotalMenuInfo] = useState({});
  //field为全部时
  const [allField, setAllField] = useState({
    ability: [],
    device_type: [],
    framework: [],
    source: [],
    task: [],
  });
  const [menuInfo, setMenuInfo] = useState({
    ability: [],
    device_type: [],
    // field: ['cv'],
    framework: [],
    source: [],
    task: [],
  });
  const [cards, setCards] = useState([]);

  //field筛选
  const [field, setField] = useState(['cv']);
  //时间筛选和名称筛选
  const [startTime, setStartTime] = useState(0);
  const [endTime, setEndTime] = useState(0);
  const [modalName_, setModalName] = useState('');

  const [pageSize, setPageSize] = useState(12);
  const [pageNum, setPageNum] = useState(1);
  const [total, setTotal] = useState(12);

  let pageQuery = props.location.query;
  useEffect(() => {
    //field级联其他选项
    studioGetRelatedTypes().then((res) => {
      if(res.code == 0 && res.data){
        setTotalMenuInfo(res.data);
        setAllField(mergeMenuInfo(res.data));
        setMenuInfo(mergeMenuInfo(res.data));
        setField('all');
        changeField('all');
      }
    });
    get_page();
  }, []);

  //合并所有field的选项
  function mergeMenuInfo(data){
    let result = {};
    let list = ['ability', 'device_type', 'framework', 'source', 'task'];
    for(let attr of list){
      result[attr] = [];
    }
    for (let key of Object.keys(data)) {
      for(let attr of list){
        result[attr] = (result[attr]).concat(data[key][attr]);
        result[attr] = Array.from(new Set(result[attr]));
      }
    }
    return result;
  }

  function get_page() {
    pageQuery = props.location.query;
    console.log(pageQuery);
    let nq = {};
    for (let key of Object.keys(pageQuery)) {
      if (pageQuery[key] != 'all') {
        nq[key] = pageQuery[key];
      }
    }
    // 应启人要求，去除 isPreload，解决 p2 问题
    console.log('pageNum', pageNum, pageSize);
    let info = { pageNum, pageSize };
    // let info = { pageNum: 1, pageSize: 40, isPreload: true };
    // TODO 此处需要动态设置
    if (nq.ability) {
      const nt_dict = {
        train: 'canTrain',
        centerInfer: 'canCenterInfer',
        edgeInfer: 'canEdgeInfer',
      };
      info[nt_dict[nq.ability]] = true;
      delete nq['ability'];
    }
    info = Object.assign(info, nq);

    if(startTime){
      info.startTime = startTime
      info.endTime = endTime
    }
    if(modalName_){
      info.name = modalName_
    }
    getModels(info).then((res) => {
      if (res && res.code === 0) {
        setCards(res.data.items);
        setTotal(res.data.total);
      }
    });
  }

  const columns = [
    {
      title: React.$i18n('镜像名称'),
      dataIndex: 'imageName',
    },

    {
      title: React.$i18n('版本数'),
      dataIndex: 'versionCount',
    },
    {
      title: React.$i18n('描述'),
      dataIndex: 'desc',
    },
    {
      title: React.$i18n('更新时间'),
      dataIndex: 'createAt',
      render: (e) => format(e),
    },
    {
      title: '操作',
      render(text, row) {
        return (
          <div>
            <span className="ldm l-text-btn danger" onClick={() => {}}>
              删除
            </span>
          </div>
        );
      },
    },
  ];
  function handleClick(a, b) {
    console.log(a, b);
  }
  function onChange() {}

  //切换field时将其他筛选条件重置为全选
  function changeField(value){
    let list = ['ability', 'deviceType', 'framework', 'source', 'task'];
    for (let key of list) {
      delete pageQuery[key];
    }
    //设置field
    if (value === 'all') {
      delete pageQuery['field'];
    } else {
      pageQuery['field'] = value;
    }
    arouter({ name: 'modelIndex', query: { field: value } });
    get_page();
  }

  function setQuery(key, value) {
    if (value === 'all') {
      delete pageQuery[key];
    } else {
      pageQuery[key] = value;
    }
    arouter({ name: 'modelIndex', query: pageQuery });
    get_page();
  }

  function selectAll() {
    let list = ['ability', 'deviceType', 'field', 'framework', 'source', 'task'];
    for (let key of list) {
      pageQuery[key] = 'all';
    }
    arouter({ name: 'modelIndex', query: { field: 'all' } });
  }
  const ref = React.useRef();

  useEffect(() => {
    get_page();
  }, [pageNum, pageSize])

  // 设置默认图片
  function setDefaultLogo(card){
    let src = 'https://www.dute.org/imgplaceholder/800x370';
    if('field' in card){
      let _field = card.field.toLowerCase();
      switch(_field){
        case 'cv':
          src = cvLogo;
          break;
        case 'nlp':
          src = nlpLogo;
          break;
        case 'recommend':
          src = recommendLogo;
          break;
        case 'speech':
          src = speechLogo;
          break;
        default:
          src = 'https://www.dute.org/imgplaceholder/800x370';
      }
    }
    return src;
  }

  return (
    <div>
      <PageContainer>
        {/* <Card> */}
          <div className={style.container}>
            <div className={style.leftSide}>
              <AuthzHOC permission="/apworkshop/api/v1/studioModelPack" action={['post']}>
                <Button type="primary" block style={{ marginBottom: '10px' }} onClick={()=>{
                  history.push(`/modelUpload`);
                }}>
                  模型上传
                </Button>
              </AuthzHOC>
              <Menu
                className={style.menu}
                // style={{marginTop: '50px'}}
                onClick={handleClick}
                // defaultSelectedKeys={pageQuery.field}
                selectedKeys={pageQuery.field}
                mode="inline"
                theme="light"
              >
                <Menu.Item
                  key="all"
                  onClick={() => {
                    setMenuInfo(allField);
                    changeField('all');
                  }}
                >
                  全部
                </Menu.Item>
                {Object.keys(totalMenuInfo).map((e) => {
                  return (
                    <Menu.Item
                      key={e}
                      onClick={() => {
                        setMenuInfo(totalMenuInfo[e]);
                        changeField(e);
                      }}
                    >
                      {e}
                    </Menu.Item>
                  );
                })}
              </Menu>
            </div>
            <div className={style.rightSide}>
              <div style={{ display: 'flex', marginBottom: '20px' }}>
                <DatePicker.RangePicker
                  showTime={{ format: 'HH:mm' }}
                  format="YYYY-MM-DD HH:mm"
                  onChange={(e, f) => {
                    console.log('change', e, f);
                    let startTime = new Date(f[0]).getTime();
                    let endTime = new Date(f[1]).getTime();
                    setStartTime(startTime);
                    setEndTime(endTime);
                  }}
                />
                <Input
                  allowClear
                  placeholder="模型名称"
                  allowClear
                  style={{ width: '200px', margin: '0px 10px' }}
                  onChange={e=>{
                    console.log(e.target,e.target.value)
                    setModalName(e.target.value)
                  }}
                />
                <Button type="primary" size="middle" onClick={get_page}>
                  搜索
                </Button>
              </div>
              <Card hoverable>

              <div className={style.selectLine}>
                <span className={style.label}>模型能力</span>
                <Radio.Group onChange={onChange} defaultValue={pageQuery.ability} value={pageQuery.ability}>
                  <Radio.Button
                    onClick={() => {
                      setQuery('ability', 'all');
                    }}
                    key="all"
                  >
                    全部
                  </Radio.Button>
                  {menuInfo && menuInfo.ability && menuInfo.ability.map((e) => {
                    return (
                      <Radio.Button
                        value={e}
                        onClick={() => {
                          setQuery('ability', e);
                        }}
                      >
                        {abilityMap[e] ? abilityMap[e]: e}
                      </Radio.Button>
                    );
                  })}
                </Radio.Group>
              </div>

                <div className={style.selectLine}>
                  <span className={style.label}>模型来源</span>
                  <Radio.Group onChange={onChange} defaultValue={pageQuery.source} value={pageQuery.source}>
                    <Radio.Button
                      onClick={() => {
                        setQuery('source', 'all');
                      }}
                      key="all"
                    >
                      全部
                    </Radio.Button>

                    {menuInfo && menuInfo.source && menuInfo.source.map((e) => {
                      return (
                        <Radio.Button
                          value={e}
                          onClick={() => {
                            setQuery('source', e);
                          }}
                        >
                          {sourceMap[e] ? sourceMap[e]: e}
                        </Radio.Button>
                      );
                    })}
                  </Radio.Group>
                </div>

                <div className={style.selectLine}>
                  <span className={style.label}>设备</span>
                  <Radio.Group onChange={onChange} defaultValue={pageQuery.device_type} value={pageQuery.deviceType}>
                    <Radio.Button
                      onClick={() => {
                        setQuery('deviceType', 'all');
                      }}
                      key="all"
                    >
                      全部
                    </Radio.Button>
                    {menuInfo && menuInfo.device_type && menuInfo.device_type.map((e) => {
                      return (
                        <Radio.Button
                          value={e}
                          onClick={() => {
                            setQuery('deviceType', e);
                          }}
                        >
                          {e}
                        </Radio.Button>
                      );
                    })}
                  </Radio.Group>
                </div>
                <div className={style.selectLine}>
                  <span className={style.label}>模型任务</span>
                  <Radio.Group onChange={onChange} defaultValue={pageQuery.task} value={pageQuery.task}>
                    <Radio.Button
                      onClick={() => {
                        setQuery('task', 'all');
                      }}
                      key="all"
                    >
                      全部
                    </Radio.Button>

                    {menuInfo && menuInfo.task && menuInfo.task.map((e) => {
                      return (
                        <Radio.Button
                          value={e}
                          onClick={() => {
                            setQuery('task', e);
                          }}
                        >
                          {e}
                        </Radio.Button>
                      );
                    })}
                  </Radio.Group>
                </div>
                <div className={style.selectLine}>
                  <span className={style.label}>框架</span>
                  <Radio.Group onChange={onChange} defaultValue={pageQuery.framework} value={pageQuery.framework}>
                    <Radio.Button
                      onClick={() => {
                        setQuery('framework', 'all');
                      }}
                      key="all"
                    >
                      全部
                    </Radio.Button>

                    {menuInfo && menuInfo.framework && menuInfo.framework.map((e) => {
                      return (
                        <Radio.Button
                          value={e}
                          onClick={() => {
                            setQuery('framework', e);
                          }}
                        >
                          {e}
                        </Radio.Button>
                      );
                    })}
                  </Radio.Group>
                </div>
                </Card>
                <div className={style.cardGroup}>
                  <Row gutter={16}>
                    {cards.map((card) => {
                      return (
                        <Col className="gutter-row" xxl={6} xl={8} lg={12} md={12} sm={12} xs={24}>
                          <Card
                            hoverable
                            style={{ marginBottom: '20px' }}
                            cover={
                              <img
                                className={style.modelImg}
                                src={
                                  card.logoPic == ''
                                    ? setDefaultLogo(card)
                                    : `data:image/png;base64,${card.logoPic}`
                                }
                              />
                            }
                            onClick={() => {
                              arouter({ name: 'modelDetail', query: { id: card.id } });
                            }}
                          >
                            <div className={style.tagGroup}>
                              {card.showList.map((e) => {
                                return <Tag style={{ marginBottom: '5px' }}>{e}</Tag>;
                              })}
                            </div>
                            <div className="card-title" style={{ display: 'flex', alignItems: 'center' }}>
                              <div
                                style={{
                                  overflow: 'hidden',
                                  textOverflow: 'ellipsis',
                                  whiteSpace: 'nowrap',
                                  flex: 1,
                                  fontSize: '20px',
                                }}
                              >
                                {card.name}
                              </div>{' '}
                              {card.latestVersionName}
                            </div>
                            <div
                              className="content"
                              style={{
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                              }}
                            >
                              {card.description}
                            </div>
                          </Card>
                        </Col>
                      );
                    })}
                  </Row>
                  <Pagination
                    pageSize={pageSize}
                    current={pageNum}
                    pageSizeOptions={[12, 24, 48, 96]}
                    showQuickJumper
                    total={total}
                    onChange={(page, pageSize) => {
                      console.log(page);
                      setPageNum(page);
                      setPageSize(pageSize);
                    }}
                  ></Pagination>
                </div>
            </div>
          </div>
        {/* </Card> */}
      </PageContainer>
    </div>
  );
};

export default ModelPage;
